package com.mec.web.y2012.coreservlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

@WebServlet("/ShowItemsServlet")
public class ShowItemsServlet extends HttpServlet {

	private static final long serialVersionUID = 8943944823391623323L;
	private static final String PREVIOUS_ITEMS = "previousItems";
	private static final String NEW_ITEM = "newItem";
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		ArrayList<String> previousItems = (ArrayList<String>) session.getAttribute(PREVIOUS_ITEMS);
		if(null == previousItems){
			previousItems = new ArrayList<String>();
			session.setAttribute(PREVIOUS_ITEMS, previousItems);
		}
		//
		String newItem = req.getParameter(NEW_ITEM);
		
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		String title = "Items Purchase";
		out.println(Constants.docType + ServletUtilities.headWithTitle(title) + 
				"<body><h1>" + title + "</h1>"
				);
		
		synchronized(previousItems){
			if(null != newItem){
				previousItems.add(newItem);
			}
		}
		//
		if(previousItems.isEmpty()){
			out.println("<em>No Item.</em>");
		}else{
			out.println("<ul>");
			for(String item : previousItems){
				out.println("<li>" + item + "</li>");
			}
			out.println("</ul>");
		}
		
		//
		out.println("</body></html>");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}




	private static final Logger logger = 
			Logger.getLogger(ShowItemsServlet.class);
}
